#include "GetProblems.h"
#include "db/DBManager.h"

#include <QDebug>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QJsonObject>
#include <QSqlError>
#include <QJsonArray>
#include <QDateTime>
#include <QSqlRecord>

void GetProblems::handleSession()
{
    QMap<QString, QString> mapQuery = m_session->requestUrlQuery();

    QString strDeviceName = mapQuery.value("device_name");
    QString strWorkerPhone = mapQuery.value("worker_phone");

    QString strSql = QString("select szProblems as problems, nWorkerConfirm as workerConfirm, "
                             "nStatus as status, dtCreateDate as time from device_request "
                             "where szDeviceName=%1 and szWorkerPhone=%2 order by nId desc limit 1");

    strSql = strSql.arg(strDeviceName).arg(strWorkerPhone);

    QSqlDatabase db = DBManager::database("core_config");
    QSqlQuery query(db);

    if(!query.exec(strSql))
    {
        qDebug()<<"exec select device_request error, "<<query.lastError().text();
        returnEmpty();
        return;
    }

    QVariantMap mapRecord;
    if (query.next())
    {
        QSqlRecord record = query.record();

        for (int i=0; i<record.count(); i++)
        {
            mapRecord.insert(record.fieldName(i), record.value(i));
        }
    }

    if (!mapRecord.isEmpty())
    {
        quint32 nTimeAccess = QDateTime::currentDateTime().toTime_t()/1000;

        QString strTimeRecord = mapRecord.value("time").toString().replace("T", " ");
        qDebug() << "strTimeRecord: " << strTimeRecord;

        quint32 nTimeRecord = QDateTime::fromString(strTimeRecord).toTime_t()/1000;

        quint32 nTimeDiff = (nTimeAccess-nTimeRecord);

        int nTimeLeft = 60*3 - nTimeDiff;

        QVariantMap mapRet;
        mapRet.insert("problems", mapRecord.value("problems").toString().split(" "));
        mapRet.insert("timeLeft", nTimeLeft<0?0:nTimeLeft);

        QJsonObject objJson = QJsonObject::fromVariantMap(mapRet);
        m_session->replyJsonObject(objJson);
    }
    else
    {
        returnEmpty();
    }
}

void GetProblems::returnEmpty()
{
    QVariantMap mapRet;
    mapRet.insert("timeLeft", 0);
    QJsonObject objJson = QJsonObject::fromVariantMap(mapRet);
    m_session->replyJsonObject(objJson);
}

